<template>
    <img height="1" width="1" style="display:none" :src="`https://www.facebook.com/tr?id=${pixel_code}&ev=PageView&noscript=1`" />
    <div class="detail-page">
        <iframe width="100%" height="100%" :src="detailUrl" frameborder="0" scrolling="no"></iframe>
    </div>
    <div class="pay_result" v-show="showPayResultStore.isPayResult">
        <div class="close" @click="close_pay_result"></div>
        <iframe :src="pay_result_src" width="100%" height="100%" frameborder="0" ></iframe>
    </div>
    <div v-if="isShowLoginStore.isShowLogin">
        <Login :isShowLogin_fn="isShowLogin_fn"/>
    </div>
</template>

<script setup>
import { useRoute } from "vue-router";
import axios from '@/utils/api'
import { useUserInfoStore } from '@/store/modules/user_info/index';
import {useIsShowLogin} from "@/store/modules/isShowLogin/index.js"
import Login from "@/components/Login/index.vue"
import Fingerprint2 from 'fingerprintjs2'
import {useShowPayResult} from "@/store/modules/isShowPayResult"
const isShowLoginStore = useIsShowLogin();
const user_infoStore = useUserInfoStore();
let user_info = reactive(user_infoStore.userInfo)
const route = useRoute();
const theater_id = route.query.id
const detailUrl = ref('');
const pay_result_src = ref('')
const showPayResultStore = useShowPayResult()
const setPayResult = (url)=>{
  showPayResultStore.showPayResult()
  pay_result_src.value = url
  console.log(pay_result_src.value,'pay_result_src.value');
}
const close_pay_result = ()=>{
    showPayResultStore.unPayResult()
    pay_result_src.value = ''
}
window.addEventListener('message', (event) => {
    // console.log(event.data,'eventevent111111');
    if(event.data.name == 'setPayResult'){
        setPayResult(event.data.url)
    }else if(event.data == 'unShow'){
        close_pay_result()
        window.location.reload()
    }
});
const isPc = () => {
  return window.innerWidth >= 1024
}

let pixel_code = ref('')
if(route.query.pixel_code){
    pixel_code.value = route.query.pixel_code
}

const setVh = ()=>{
    let vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
}
onMounted(()=>{
    setVh()
})
const isShowLogin_fn = ()=>{
    isShowLoginStore.unShowLogin()
}
const isApp = ()=>{
    if (typeof webkit !== 'undefined' || typeof AndroidInterface !== 'undefined') {
        return true;
    } else {
        return false;
    }
}

function isFacebookBrowser() {
    const ua = navigator.userAgent;
    return /FBAN|FBAV/i.test(ua);
}

const tourist = ref(false)
const tourist_login = async () =>{

    Fingerprint2.get(async (components) => {
        const values = components.map((component) => component.value) 
        const fingercode = Fingerprint2.x64hash128(values.join(''), 31) 
        console.log('浏览器指纹：',fingercode) 

        if(route.query.type == undefined){
            route.query.type = ''
        }
        const res = await axios.get('/tourist_register_login?theater_id='+route.query.id+'&type='+route.query.type+'&code='+fingercode)
        console.log(res);
        // isShowLoginStore.isShowLogin = true
        if(res.code === 1){
            // ElMessage.success('游客登陸')
            user_infoStore.setUserToken(res.data.token)
            user_infoStore.setUserToken_expire(res.data.expire)
            user_infoStore.setUserinfo(res.data.user_info)
            tourist.value = true
            
            console.log('注册-CompleteRegistration',fbq);
            localStorage.setItem('CompleteRegistration',1)
            
            if(isFacebookBrowser()){
                window.location.reload()
            }else if(isApp()){
                if(isDevice() == 'ios'){
                    window.location.reload()
                }else if(isDevice() == 'android'){
                    AndroidInterface.resetWeb("网页调用了 Android 方法");
                }
                console.log('网页调用了 Android 方法')
            }else{
                console.log('网页调用了 window.location.reload ')
                window.location.reload()
            }
            
            // isShowLoginStore.unShowLogin() //关闭登录弹窗
            // router.replace('/home')
        }else{
            ElMessage.error(res.message)
        }
    })    
    
    
}

!function (f, b, e, v, n, t, s) {
      if (f.fbq) return; n = f.fbq = function () {
        n.callMethod ?
        n.callMethod.apply(n, arguments) : n.queue.push(arguments)
      };
      if (!f._fbq) f._fbq = n; n.push = n; n.loaded = !0; n.version = '2.0';
      n.queue = []; t = b.createElement(e); t.async = !0;
      t.src = v; s = b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t, s)
}(window, document, 'script','https://connect.facebook.net/en_US/fbevents.js');
fbq('init', pixel_code.value);

if(localStorage.getItem('CompleteRegistration') == 1){
    fbq('track', 'CompleteRegistration')
    localStorage.setItem('CompleteRegistration',0)
}

if(!user_info.id){
    if((!isApp() || isFacebookBrowser())){
        tourist_login()//游客无感登录
    }else{
        isShowLoginStore.showLogin()
    }
}else{
    let hostname = ''
    let episode = ''
    if(import.meta.env.DEV){
        hostname = 'localhost:5173'
    }else{
        hostname = '//'+window.location.hostname
    }
    if(route.query.episode){
        episode = route.query.episode
    }
    if(isPc()){
        detailUrl.value = hostname+'/#/home/SandSculptureDetail?id='+theater_id+'&episode='+episode
    }else{
        detailUrl.value = hostname+'/h5/#/pages/Home/sandSculptureDetail/index?id='+theater_id+'&episode='+episode
    }
    console.log('detailUrl.value',detailUrl.value);
    
}

window.addEventListener('message', (event) => {
    if(event.data.type == 'AddToCart'){
        console.log('发起支付-AddToCart',fbq);
        fbq('track', 'AddToCart',{value:event.data.price,currency:'USD',time:new Date().getTime()}); 
    }
})
</script>

<style lang="less" scoped>
@media (max-width: 1024px) {
    .detail-page{
        height: calc(var(--vh, 1vh) * 100) !important;
    }
}
.detail-page{
    width: 100%;
    height: calc(var(--vh, 1vh) * 100);
    overflow: hidden;
}
.pay_result{
    background-color: #fff;
    width: 600px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10000;
    height: 700px;
    border-radius: 15px;
    overflow: hidden;
    iframe{
        border-radius: 15px;
        position: relative;
        z-index: 2003;
    }
    .close{
      z-index: 9999;
    }
    .close:hover {
        cursor: pointer;
        background-image: url();
    }
}
</style>